# -*- coding:utf-8 -*-
import json
from app.tools.timestamp import dealine
from app.tools.message import message
from app.tools.log import log
from app.views.risk.dispatch import dispatch as main
from app.models.risk_manage import Risk_Flow, Risk_Application as RA, RiskPicture
from app.models.account import Staff
from app.tools.permission import permission
from .. import *


def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


main.before_request(signin_required)


@main.before_request
@login_required
@permission(['director', 'admin', 'super'])
def check_permission():
    return


@main.route('/')
def lists():
    services = Staff.query.filter_by(role='service').all()
    staff_dict = {}
    name_dict = {}
    for s in services:
        name = s.name
        staff_number = s.staff_number
        staff_dict[staff_number] = name
        name_dict[name] = staff_number
    return render_template('risk/dispatch/list.html',
                           staff_dict=staff_dict,
                           name_dict=name_dict,
                           json=json
                           )


@main.route('/get_list')  # 跟进分配 列表
def get_list():
    limit = int(request.values.get('limit', '10'))
    offset = int(request.values.get('offset', '0'))
    list_type = request.values.get('list_type')
    if list_type is None:
        return jsonify({'state': -1, 'msg': u'参数不足'})
    if list_type == 'dispatch':
        query = RA.query.order_by(RA.timestamp_app.desc()). \
            paginate(offset / limit + 1, limit, False)
    else:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    result = query.items
    total = query.total
    data = []
    for item in result:
        s = Staff.query.filter_by(staff_number=item.initiator).first()
        d = u'正常'
        if s.account_state == 1:
            d = u'冻结'
        data.append({
            'id': item.id,
            'flow_id': item.flow_id,
            'pledge_type': item.pledge_type,
            'amount': item.amount,
            'days': item.days,
            'area': item.area,
            'name': item.name + '(' + item.person_type + ')',
            'initiator': item.initiator,
            'account_state': d,
            'status': item.flow_status,
            'operate': str(s.account_state),
        })
    json = {'total': total, 'rows': data}
    return jsonify(json)


@main.route('/dispatch', methods=['POST'])
def reset():
    form = request.form
    print form
    flow_id = form.get('flow_id')
    initiator = form.get('initiator')
    name = form.get('name')
    staff_number = form.get('staff_number')
    ra = RA.query.filter_by(flow_id=flow_id).first()
    s = Staff.query.filter_by(name=name, staff_number=staff_number).first()
    if not s:
        flash(u'分配失败,该帐号不存在或工号与名字不匹配')
        return redirect(url_for('.lists'))
    elif s.account_state == 0:
        if ra.flow_status == u'申请':
            ra.initiator = staff_number
            ra.save()
            flash(u'分配成功')
            msg = u'流程 {} 已由 【{}】 分派给【{}】'.format(flow_id, session['name'], name)

            log(msg)
            message(msg, u'分单', server_id=staff_number)
            return redirect(url_for('.lists'))
        else:
            last_staff = Staff.query.filter_by(staff_number=ra.initiator).first().name
            ra.initiator = staff_number
            ra.save()
            flash(u'修改跟进人成功')
            msg = u'流程 {} 跟进人从 【{}】更改为【{}】'.format(flow_id, last_staff, name)

            log(msg)
            message(msg, u'分单', server_id=staff_number)
            return redirect(url_for('.lists'))
    elif s.account_state == 1:
        flash(u'分配失败,该帐号已被冻结')
        return redirect(url_for('.lists'))
